package cn.huiyunche.admin.utils;

import java.util.List;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import cn.huiyunche.base.service.enums.AvailableEnum;
import cn.huiyunche.base.service.framework.utils.JdbcTemplateUtils;
import cn.huiyunche.base.service.model.SysAdminUser;

/**
 * 知车客运段端工具类
 * @author hdy [Tuffy]
 *
 */
@Component
public class AdminUtils{
	
	/**
	 * 获取用户菜单列表
	 * @return
	 */
	public static Long userFirstMenuList() {
		List<Long> list = getMenuIdsByRole(getSysAdminUserRole(getSysAdminUserId()));
		if (null == list || list.size() == 0) {
			return 0L;
		}
		return list.get(0);
	}
	
	/**
	 * 获取用户菜单列表
	 * @return
	 */
	public static List<Long> userMenuList() {
		return getMenuIdsByRole(getSysAdminUserRole(getSysAdminUserId()));
	}
	
	/**
	 * 获取用户角色
	 * @param userId
	 * @return
	 */
	public static Long getSysAdminUserRole(Long userId) {
		String sql = "select role_id from sys_admin_role_user where user_id = " + userId;
		return JdbcTemplateUtils.getJdbcTemplate().queryForObject(sql, Long.class);
	}
	
	/**
	 * 获取当前用户Id
	 * @param username
	 * @return
	 */
	public static Long getSysAdminUserId() {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		UserDetails ud = (UserDetails) authentication.getPrincipal();
		if (null != ud) {
			String username = ud.getUsername();
			String sql = "select id from sys_admin_user where username = '" + username + "'";
			return JdbcTemplateUtils.getJdbcTemplate().queryForObject(sql, Long.class);
		}
		return null;
	}
	
	/**
	 * 获取当前用户
	 * @return
	 */
	public static SysAdminUser getSysAdminUser() {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		UserDetails ud = (UserDetails) authentication.getPrincipal();
		if (null != ud) {
			String username = ud.getUsername();
			String sql = "select id from sys_admin_user where username = '" + username + "' and enabled = '" + AvailableEnum.T.getValue() + "'";
			SysAdminUser sau = new SysAdminUser();
			sau.setId(JdbcTemplateUtils.getJdbcTemplate().queryForObject(sql, Long.class));
			sau.setUsername(username);
			sau.setPassword(null);
			sau.setEnabled(AvailableEnum.T.getValue());
			return sau;
		}
		return null;
	}
	
	/**
	 * 根据角色查询菜单列表
	 * @return
	 */
	public static List<Long> getMenuIdsByRole(Long roleId) {
		String sql = "select menu_id from sys_admin_menu_role where role_id = " + roleId;
		return JdbcTemplateUtils.getJdbcTemplate().queryForList(sql, Long.class);
	}

}
